﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using VOD.Models;
using VOD.Helpers;
using System.Web.Helpers;
using VOD.ViewModels;
using PagedList;
using System.Data;

namespace VOD.Areas.Admin.Controllers
{
    [Authorize(Roles = "Administrators")]
    public class VideoMgrController : Controller
    {
        VODEntities db = new VODEntities();
        //
        // GET: /VideoMgr/
        public ActionResult Index()
        {
            return RedirectToAction("Category");
        }

        /// <summary>
        /// 添加视频步骤1，选择视频分类Category
        /// </summary>
        /// <returns></returns>
        public ActionResult Step1()
        {
            var categories = db.VideoCategories.Where(v=>v.CategoryID!=1 && v.CategoryID!=6).ToList();
            return View(categories);
        }
        
        /// <summary>
        /// 添加视频步骤2，填写视频信息（基于Video类）
        /// </summary>
        /// <param name="CategoryID">步骤1传来的视频分类ID，默认为1（其他）</param>
        /// <returns></returns>
        public ActionResult Step2(int CategoryID=1)
        {
            ViewBag.LangID = new SelectList(db.VideoLanguages, "LangID", "LangName");
            ViewBag.AreaID = new SelectList(db.VideoAreas, "AreaID", "AreaName");
            var types = db.VideoTypes.Where(t => t.CategoryID == CategoryID).ToList();
            var viewModel = new List<AssignedTypeData>();
            foreach (var type in types)
            {
                viewModel.Add(new AssignedTypeData
                {
                    TypeID = type.TypeID,
                    TypeName = type.TypeName,
                    Assigned = false
                });
            }
            ViewBag.Types = viewModel;
            ViewBag.CategoryName = db.VideoCategories.SingleOrDefault(c => c.CategoryID == CategoryID).CategoryName;
            var video = new Video
            {
                CategoryID = CategoryID,
                AddDate = DateTime.Now,
                UpdateDate=DateTime.Now
            };
            if (CategoryID == 5)
            {
                return View("Variety",new Video());
            }
            return View(video);
        }

        /// <summary>
        /// 步骤2，保存视频信息，post方式
        /// </summary>
        /// <param name="video"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Step2(int CategoryID,Video video, int[] Types)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    //1.插入视频信息
                    video.AddDate = DateTime.Now;
                    video.UpdateDate = video.AddDate;
                    db.Videos.Add(video);
                    db.SaveChanges();
                    int videoID = video.VideoID;
                    //2.插入视频类别
                    if (Types != null)
                    {
                        foreach (var type in Types)
                        {
                            db.VideoAndTypes.Add(new VideoAndType
                            {
                                TypeID = type,
                                VideoID = videoID
                            });
                        }
                        db.SaveChanges();
                    }
                    //3.保存上传的图片
                    WebImage pic = WebImage.GetImageFromRequest("PicUrl");
                    UploadImage(videoID,pic);
                    return RedirectToAction("Step3", new { id = videoID });
                } 
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "添加出错，请检查后重新提交！");
            }
            ViewBag.LangID = new SelectList(db.VideoLanguages, "LangID", "LangName");
            ViewBag.AreaID = new SelectList(db.VideoAreas, "AreaID", "AreaName");
            var types = db.VideoTypes.Where(t => t.CategoryID == video.CategoryID).ToList();
//             var inputTypes = HashSet<int>(Types.Select(t=>t));
            var viewModel = new List<AssignedTypeData>();
            //添加类别
            foreach (var type in types)
            {
                viewModel.Add(new AssignedTypeData
                {
                    TypeID = type.TypeID,
                    TypeName = type.TypeName,
                    Assigned = false
                });
            }
            ViewBag.Types = viewModel;
            ViewBag.CategoryName = db.VideoCategories.SingleOrDefault(c => c.CategoryID == video.CategoryID).CategoryName;
            if (CategoryID == 5)
            {
                return View("Variety", video);
            }
            return View(video);
        }

        private void UploadImage(int videoID,WebImage pic)
        {
            if (pic != null)
            {
                //等比例缩放到230*306左右
                if (pic.Height > 306 || pic.Width > 230)
                {
                    double percent = pic.Height / pic.Width;
                    percent = percent > 1.34 ? 230.0 / pic.Width : 306.0 / pic.Height;
                    pic = pic.Resize((int)(pic.Width * percent), (int)(pic.Height * percent), preventEnlarge: true);
                }
                var imgFile = videoID.ToString() + ".jpg";
                var picPath = Server.MapPath("~/Content/images/VideoImg/" + imgFile);
                pic.Save(picPath, forceCorrectExtension: false);
            }
        }

        /// <summary>
        /// 添加视频步骤3，添加视频文件地址
        /// </summary>
        /// <param name="id">步骤2的视频ID</param>
        /// <returns></returns>
        public ActionResult Step3(int id)
        {
            //var video = db.Videos.Find(id);
            //return View(video);
            var video = db.Videos.Single(v => v.VideoID == id);
            return View("EditFiles",video);
        }

        [HttpPost]
        public ActionResult Step3(int id, string fileUrlList)
        {
            //3.获取视频文件列表
            List<VideoFileList> json = JsonHelper.JsonDeserialize<List<VideoFileList>>(fileUrlList);
            VideoUrl videoUrl = new VideoUrl();
            foreach (var file in json)
            {
                videoUrl.VideoOrder = file.Num + 1;
                videoUrl.VideoURL = file.Url;
                videoUrl.VideoID = id;
                db.VideoUrls.Add(videoUrl);
            }
            db.SaveChanges();
            return Content("Succeed!");
        }

        //
        // GET: /VideoMgr/Edit/5
        public ActionResult EditInfo(int id)
        {
            var video = db.Videos
                .Include(v => v.VideoAndTypes.Select(t => t.VideoType)).Single(v => v.VideoID == id);
            ViewBag.LangID = new SelectList(db.VideoLanguages, "LangID", "LangName",video.LangID);
            ViewBag.AreaID = new SelectList(db.VideoAreas,"AreaID","AreaName",video.AreaID);
            PopulateAssignedTypesData(video);
            return View(video);
        }

        /// <summary>
        /// 生成复选框组
        /// </summary>
        /// <param name="video">视频类</param>
        private void PopulateAssignedTypesData(Video video)
        {
            var allTypes = db.VideoTypes.Where(t => t.CategoryID == video.CategoryID);
            var videoTypes = new HashSet<int>(video.VideoAndTypes.Select(t => t.TypeID));
            var viewModel = new List<AssignedTypeData>();
            foreach (var type in allTypes)
            {
                viewModel.Add(new AssignedTypeData
                {
                    TypeID = type.TypeID,
                    TypeName = type.TypeName,
                    Assigned = videoTypes.Contains(type.TypeID)
                });
            }
            ViewBag.Types = viewModel;
        }

        [HttpPost]
        public ActionResult EditInfo(int id, Video video, int[] Types)
        {
            var videoToUpdate = db.Videos
                .Include(v => v.VideoAndTypes).Single(v => v.VideoID == id);
            try
            {
                videoToUpdate.UpdateDate = DateTime.Now;
                UpdateModel(videoToUpdate, "", null, new string[] { "VideoAndTypes" });
                UpdateVideoTypes(Types, videoToUpdate);
                db.Entry(videoToUpdate).State = EntityState.Modified;
                db.SaveChanges();
                WebImage pic = WebImage.GetImageFromRequest("PicUrl");
                UploadImage(id, pic); ;
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        private void UpdateVideoTypes(int[] types, Video videoToUpdate)
        {
            if (types == null)
            {
                videoToUpdate.VideoAndTypes = new List<VideoAndType>();
                return;
            }
            //客户端已选typeID
            var selectTypes = new HashSet<int>(types);
            //数据库已存typeID
            var videoTypes = new HashSet<int>(videoToUpdate.VideoAndTypes.Select(t => t.TypeID));
            //数据库中Category下的所有Type
            var allTypes=db.VideoTypes.Where(t=>t.CategoryID==videoToUpdate.CategoryID);
            foreach (var type in allTypes)
            {
                if (selectTypes.Contains(type.TypeID))
                {
                    //如果数据库不存在客户端所选择的TypeID，则videoToUpdate添加该类
                    if (!videoTypes.Contains(type.TypeID))
                    {
                        videoToUpdate.VideoAndTypes.Add(new VideoAndType
                        {
                            TypeID = type.TypeID,
                            VideoID = videoToUpdate.VideoID
                        });
                    }
                }
                else
                {
                    //如果数据库中存在客户端所选TypeID，则videoToUpdate删除此类
                    if (videoTypes.Contains(type.TypeID))
                    {
                        videoToUpdate.VideoAndTypes.Remove(new VideoAndType
                        {
                            TypeID = type.TypeID,
                            VideoID = videoToUpdate.VideoID
                        });
                    }
                }
                
            }
        }

        public ActionResult EditFiles(int id)
        {
            var video = db.Videos
                .Include(v => v.VideoUrls).Single(v => v.VideoID == id);
            return View(video);
        }
        
        /// <summary>
        /// 后台显示电影详细信息
        /// </summary>
        /// <param name="id">VideoID</param>
        /// <returns></returns>
        public ActionResult Details(int id)
        {
            var video = db.Videos
                .Include(v => v.VideoArea)
                .Include(v => v.VideoLanguage)
                .Include(v => v.VideoCategory)
                .Include(v => v.VideoAndTypes)
                .Include(v => v.PlayRecords)
                .Include(v=>v.VideoUrls).Single(v => v.VideoID == id);
            return View(video);
        }

        //
        // GET: /Movie/Delete/5
        public ActionResult Delete(int id)
        {
            var video = db.Videos.Find(id);
            return View(video);
        }

        //
        // POST: /Movie/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            var video = db.Videos.Find(id);
            video.Recycled = 1;
            db.Entry(video).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        // 视频列表
        // GET: Admin/VideoMgr/Category/5
        public ActionResult Category(int? id,string searchString,string currentFilter,int? page)
        {
            var videos = db.Videos
                        .Include(v => v.VideoAndTypes.Select(t=>t.VideoType))
                        .Include(v => v.VideoLanguage)
                        .Include(v => v.VideoArea)
                        .Where(v => v.Recycled != 1);
            if (id>0)
            {
                videos = videos.Where(v => v.CategoryID == id);
            }
            if (string.IsNullOrEmpty(searchString))
            {
                searchString = currentFilter;
            } 
            else
            {
                page = 1;
            }
            ViewBag.CurrentFilter = searchString;
            if (!String.IsNullOrEmpty(searchString))
            {
                videos = videos.Where(s => s.Name.ToUpper().Contains(searchString.ToUpper()));
            }
            videos = videos.OrderByDescending(v => v.UpdateDate);
            ViewBag.ID = id;
            //分页，使用PageList
            int pageSize = 10;//定义每页显示的记录数
            int pageNumber = page ?? 1;
            return View(videos.ToPagedList(pageNumber,pageSize));
        }

        // 所有类别，用于生成左栏菜单
        // GET: Admin/VideoMgr/AllCategories
        public ActionResult AllCategories()
        {
            var categories = db.VideoCategories.Where(v=>v.CategoryID!=6).ToList();
            return View(categories);
        }

        public ActionResult NoFile(int? page)
        {
            var videos = db.Videos
                        .Include(v => v.VideoAndTypes.Select(t => t.VideoType))
                        .Include(v => v.VideoLanguage)
                        .Include(v => v.VideoArea)
                        .Include(v => v.VideoUrls)
                        .Where(v => v.Recycled != 1 && v.VideoUrls.Count < 1)
                        .OrderByDescending(v => v.AddDate);
            //分页，使用PageList
            int pageSize = 10;//定义每页显示的记录数
            int pageNumber = page ?? 1;
            return View(videos.ToPagedList(pageNumber, pageSize));
        }

        #region Ajax调用

        /// <summary>
        /// 显示文件列表
        /// </summary>
        /// <param name="id">视频ID</param>
        /// <returns></returns>
        public ActionResult FilesList(int id)
        {
            var files = db.VideoUrls.OrderBy(u => u.VideoOrder).Where(v => v.VideoID == id);
            return PartialView(files);
        }

        /// <summary>
        /// 添加视频文件记录
        /// </summary>
        /// <param name="videoID">视频ID</param>
        /// <param name="orderNum">集数</param>
        /// <param name="fileUrl">视频路径</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CreateFile(int videoID,int orderNum,string fileUrl)
        {
            if (Request.IsAjaxRequest())
            {
                var video = db.Videos
                    .Include(v => v.VideoUrls).Single(v => v.VideoID == videoID);
                video.VideoUrls.Add(new VideoUrl
                {
                    VideoOrder = orderNum,
                    VideoURL = fileUrl,
                    VideoID = video.VideoID,
                    AddDate = DateTime.Now
                });
                db.Entry(video).State = EntityState.Modified;
                db.SaveChanges();
                return Content("succeed");
            }
            return Content("faild");
        }

        /// <summary>
        /// 删除视频文件记录
        /// </summary>
        /// <param name="videoPartID">文件ID</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DeleteFile(int videoPartID)
        {
            if (Request.IsAjaxRequest())
            {
                var file = new VideoUrl { VideoPartID = videoPartID };
                db.Entry(file).State = EntityState.Deleted;
                db.SaveChanges();
                return Content("succeed");
            }
            return Content("faild");
        }

        [HttpPost]
        public ActionResult EditFile(int videoPartID, int orderNum, string fileUrl)
        {
            if (Request.IsAjaxRequest())
            {
                var file = db.VideoUrls.Find(videoPartID);
                file.VideoURL = fileUrl;
                file.VideoOrder = orderNum;
                db.Entry(file).State = EntityState.Modified;
                db.SaveChanges();
                return Content("succeed");
            }
            return Content("faild");
        }

        public class cFilesList
        {
            public int partID { get; set; }
            public int orderNum { get; set; }
        }

        [HttpPost]
        public ActionResult SortFiles(int videoID,string filesList)
        {
            if (Request.IsAjaxRequest())
            {
                if (String.IsNullOrEmpty(filesList))
                {
                    return Content("faild");
                }
                var files = JsonHelper.JsonDeserialize<List<cFilesList>>(filesList);
                var dbFiles = db.VideoUrls.Where(f => f.VideoID == videoID);
                foreach (var file in dbFiles)
                {
                    file.VideoOrder = files.Single(f => f.partID == file.VideoPartID).orderNum;
                }
                db.SaveChanges();
                return Content("succeed");
            }
            return Content("faild");
        }

        #endregion

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
